package com.jihui.enterprise.common;

import com.jihui.security.web.userdetails.JihuiWebSecurityConfigurerAdapter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
//import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * web security config
 *
 * @author linux_china
 */
@Configuration
@EnableWebSecurity
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class EnterpriseWebSecurityConfigurerAdapter extends JihuiWebSecurityConfigurerAdapter {

    private String[] whiteTradeWebUrls = new String[]{"/jsondoc", "/jsondoc-ui.html", "**/*.css", "/webjars/**", "**/*.js", "**/*.map", "*.html,", "/healthchecking","/health","/metrics"};
    //@Value("${info.buyer.domain}")
    private String buyerDomain;

    @Override
    protected void internalConfigure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(whiteTradeWebUrls).permitAll()
                .antMatchers("/", "/order_confirm", "/buy_directly/**")
                .hasAnyAuthority("seller")
                .anyRequest().authenticated();
    }

    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(whiteTradeWebUrls);
    }

    /**
     * add interceptors
     *
     * @param registry interceptor registry
     */
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptorAdapter() {
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                return true;
            }
        });
    }

    protected String getRedirect() {
        return buyerDomain;
    }
}